package com.jxtc.enterprise.admin.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jxtc.enterprise.common.aspectj.TokenRequired;
import com.jxtc.enterprise.common.constants.PrinterTypeEnum;
import com.jxtc.enterprise.common.entity.Store;
import com.jxtc.enterprise.common.entity.Tenant;
import com.jxtc.enterprise.common.mapper.StoreMapper;
import com.jxtc.enterprise.common.mapper.TenantMapper;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultCode;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 管理员端，店铺管理，新增，编辑，删除，查找店铺
 */
@RestController
@RequestMapping("/jxtc/enterprise/admin/storeManage")
@Slf4j
@TokenRequired(role = TokenRequired.ROLE_ADMIN)
public class AdminStoreManageController {

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private TenantMapper tenantMapper;


    /**
     * 根据店铺名称，模糊查询店铺，查询某个租户 挖掘合作的店铺列表
     * @param keyword
     * @return
     */
    @Operation(summary = "1.4.1 管理员查询整个平台各个租户合作的店铺列表", tags = {"1.4 管理员店铺管理"}, operationId = "1.4.1")
    @GetMapping("/queryStoreByKeywordAdminView")
    public Result<?> queryStoreByKeywordAdminView(
            @RequestParam(value = "tenantName", required = false) String tenantName,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {

        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, admin view, /queryStoreByKeywordAdminView, tenantName: {}, keyword: {}", requestId, tenantName, keyword);
        // 支持页面上租户名输入框输入 租户名或租户手机号，支持模糊查询
        List<Tenant> tenants = tenantMapper.selectList(
                new LambdaQueryWrapper<Tenant>().like(Tenant::getNickname, tenantName).or().like(Tenant::getPhone, tenantName));

        if (CollectionUtil.isEmpty(tenants)) {
            Result<JSONObject> result = new Result<>();
            result.setCode(ResultCode.SUCCESS);
            JSONObject resultData = new JSONObject();
            resultData.put("currentPage", pageNo);
            resultData.put("totalPages", 0);
            resultData.put("totalRows", 0);
            resultData.put("stores", null);
            result.setData(resultData);

            log.warn("requestId {}, admin view, /queryStoreByKeywordAdminView, can't find tenant match search text, tenantName: {}, keyword: {}",
                    requestId, tenantName, keyword);
            return result;
        }

        Map<String, Tenant> tenantIdToVoMap = tenants.stream().collect(Collectors.toMap(Tenant::getId, Function.identity()));

        Page page = new Page(pageNo, pageSize);
        Page<Store> list = storeMapper.selectPage(page,
                new LambdaQueryWrapper<Store>()
                        .like(Store::getName, keyword)
                        .in(Store::getTenantId, tenantIdToVoMap.keySet())
                        .eq(Store::getDelFlag, false));
        List<JSONObject> formatedList = new ArrayList<>();
        list.getRecords().forEach(store -> {
            // 主要是为了 返回转换成小数的店铺合作价格，同时不返回 del_flag, create_time, last_update_time，才进行如下操作
            Float storePriceInYuan = 1.0F * store.getStorePrice() / 100;
            JSONObject formatedStoreInfo = new JSONObject();
            formatedStoreInfo.put("id", store.getId());
            formatedStoreInfo.put("name", store.getName());
            formatedStoreInfo.put("logo", store.getLogo());
            formatedStoreInfo.put("address", store.getAddress());
            formatedStoreInfo.put("longitude", store.getLongitude());
            formatedStoreInfo.put("latitude", store.getLatitude());
            formatedStoreInfo.put("description", store.getDescription());
            formatedStoreInfo.put("foodTypes", store.getFoodTypes());
            formatedStoreInfo.put("merchantIdNum", store.getMerchantIdNum());
            formatedStoreInfo.put("merchantPhone", store.getMerchantPhone());
            formatedStoreInfo.put("merchantWechatNum", store.getMerchantWechatNum());
            formatedStoreInfo.put("merchantName", store.getMerchantName());
            formatedStoreInfo.put("businessStart", store.getBusinessStart());
            formatedStoreInfo.put("businessEnd", store.getBusinessEnd());
            formatedStoreInfo.put("qualification", store.getQualifications());
            formatedStoreInfo.put("storePrice", storePriceInYuan);
            formatedStoreInfo.put("merchantLoginPasswd",store.getMerchantLoginPasswd());
            formatedStoreInfo.put("limitCount",store.getLimitCount());
            formatedStoreInfo.put("printerSn",store.getPrinterSn());
            formatedStoreInfo.put("mergeFoodItems",store.getMergeFoodItems());
            formatedStoreInfo.put("tenantId", store.getTenantId());
            formatedStoreInfo.put("tenantName", tenantIdToVoMap.get(store.getTenantId()).getNickname());

            if (store.getPrintLabelType().intValue() == 1) {
                // 数据库中 print_label_type 列的值 1：贴纸
                formatedStoreInfo.put("printerType", PrinterTypeEnum.TIE_ZHI_PRINTER.getPrinterTypeName());
            } else if (store.getPrintLabelType().intValue() == 2) {
                // 数据库中 print_label_type 列的值 2：外卖小票
                formatedStoreInfo.put("printerType", PrinterTypeEnum.XIAO_PIAO_PRINTER.getPrinterTypeName());
            } else {
                log.error("requestId: {}, admin view, /queryStoreByKeywordAdminView, 管理平台，根据关键字，查询店铺列表接口，获取打印机类型异常，店铺详情：{}",requestId, store);
            }

            formatedList.add(formatedStoreInfo);
        });

        Result<JSONObject> result = new Result<>();
        result.setCode(ResultCode.SUCCESS);
        JSONObject resultData = new JSONObject();
        resultData.put("currentPage", pageNo);
        resultData.put("totalPages", list.getPages());
        resultData.put("totalRows", list.getTotal());
        resultData.put("stores", formatedList);
        result.setData(resultData);
        log.info("requestId {}, admin view, /queryStoreByKeywordAdminView, response successfully", requestId);
        return result;
    }


    /**
     * 根据店铺id获取店铺详情
     * @param storeId
     * @return
     */
    @Operation(summary = "1.4.2 管理员查看某个店铺详情", tags = {"1.4 管理员店铺管理"}, operationId = "1.4.2")
    @GetMapping("/queryStoreDetailByStoreIdAdminView")
    public Result<?> queryStoreDetailByStoreIdAdminView(@RequestParam(value = "storeId") String storeId){

        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, admin view, /queryStoreDetailByStoreIdAdminView, storeId: {}", requestId, storeId);
        Store store = storeMapper.selectById(storeId);

        // 主要是为了 返回转换成小数的店铺合作价格，同时不返回 del_flag, create_time, last_update_time，才进行如下操作
        Float storePriceInYuan = 1.0F * store.getStorePrice() / 100;
        JSONObject formatedStoreInfo = new JSONObject();
        formatedStoreInfo.put("id", store.getId());
        formatedStoreInfo.put("name", store.getName());
        formatedStoreInfo.put("logo", store.getLogo());
        formatedStoreInfo.put("address", store.getAddress());
        formatedStoreInfo.put("longitude", store.getLongitude());
        formatedStoreInfo.put("latitude", store.getLatitude());
        formatedStoreInfo.put("description", store.getDescription());
        formatedStoreInfo.put("foodTypes", store.getFoodTypes());
        formatedStoreInfo.put("merchantIdNum", store.getMerchantIdNum());
        formatedStoreInfo.put("merchantPhone", store.getMerchantPhone());
        formatedStoreInfo.put("merchantWechatNum", store.getMerchantWechatNum());
        formatedStoreInfo.put("merchantName", store.getMerchantName());
        formatedStoreInfo.put("businessStart", store.getBusinessStart());
        formatedStoreInfo.put("businessEnd", store.getBusinessEnd());
        formatedStoreInfo.put("qualification", store.getQualifications());
        formatedStoreInfo.put("storePrice", storePriceInYuan);
        formatedStoreInfo.put("merchantLoginPasswd",store.getMerchantLoginPasswd());
        formatedStoreInfo.put("limitCount",store.getLimitCount());
        formatedStoreInfo.put("printerSn",store.getPrinterSn());
        formatedStoreInfo.put("mergeFoodItems",store.getMergeFoodItems());

        if (store.getPrintLabelType().intValue() == 1) {
            // 数据库中 print_label_type 列的值 1：贴纸
            formatedStoreInfo.put("printerType", PrinterTypeEnum.TIE_ZHI_PRINTER.getPrinterTypeName());
        } else if (store.getPrintLabelType().intValue() == 2) {
            // 数据库中 print_label_type 列的值 2：外卖小票
            formatedStoreInfo.put("printerType", PrinterTypeEnum.XIAO_PIAO_PRINTER.getPrinterTypeName());
        } else {
            log.error("requestId: {}, admin view, /queryStoreDetailByStoreIdAdminView, 管理平台，根据关键字，查询店铺列表接口，获取打印机类型异常，店铺详情：{}",requestId, JSONObject.toJSONString(store));
        }

        return ResultGenerator.genSuccessResult(formatedStoreInfo);
    }

}
